import { useState } from 'react'
import { connect } from 'react-redux'
import { useRouteMatch } from 'react-router-dom'
import React from 'react'
import { Link } from 'react-router-dom'
import 'antd/dist/antd.css'
import '../index.css'
import { Form, Input, Button } from 'antd'

function User({ list, dispatch }) {
  const {
    params: { id },
  } = useRouteMatch()

  const [newUserName, setNewUserName] = useState('')
  const [newAge, setNewAge] = useState('')
  const [newAddress, setNewAddress] = useState('')

  const actualUser = list.find(user => user.id === id)

  function updateUserHandler() {
    dispatch({
      type: 'update_user',
      payload: {
        user: {
          ...actualUser,
          name: newUserName,
          age: newAge,
          address: newAddress,
        },
      },
    })
  }

  const layout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 10,
    },
  }
  const tailLayout = {
    wrapperCol: {
      offset: 8,
      span: 16,
    },
  }

  return (
    <Form {...layout}>
      <Form.Item label="姓名：" value="username">
        <Input
          placeholder={actualUser.name}
          onChange={e => setNewUserName(e.target.value)}
        />
      </Form.Item>

      <Form.Item label="年龄：" value="age">
        <Input
          placeholder={actualUser.age}
          onChange={e => setNewAge(e.target.value)}
        />
      </Form.Item>

      <Form.Item label="地址：" value="address">
        <Input
          placeholder={actualUser.address}
          onChange={e => setNewAddress(e.target.value)}
        />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit" onClick={updateUserHandler}>
          修改用户
        </Button>
        <Button type="primary" htmlType="submit">
          <Link to={'/list'}>返回</Link>
        </Button>
      </Form.Item>
    </Form>
  )
}

export default connect(({ list }) => ({ list }))(User)
